<template>
  <view>
    <view class="media_container">
      <!--图片列表-->
      <ImageList v-if="fileType=='png'||fileType=='jpg'" :list="mediaList"></ImageList>
      <!--视频展示-->
      <videoPreview v-if="fileType =='mp4'" :src="videoSrc" :poster="coverUrl"></videoPreview>

      <!--pdf docx 等预览-->
      <!-- <SsPreview v-if="fileType>=2" fileType="2" :fileUrl="previewUrl"  /> -->
      <view class="fileplaceholder" v-if="showPreview" @click="showFile">

        <view class="tag">HUIDA 惠达</view>

        <mumu-previewOffce ref="previewOffice" :fileUrl='previewUrl' v-model='showPreview' @change="onChange"
          @openSuccess="onSuccess" @openFailed="openFailed"></mumu-previewOffce>
        <image mode="aspectFit" class="placeholder" :src="coverUrl"></image>
      </view>


    </view>
    <view v-if="showOption" class="bottom-contianer">
      <!-- <view class="number-indicator">
        <text class="current">{{ activeIndex + 1 }}</text>
        <text class="slash">/</text>
        <text class="total">{{ mediaList.length }}</text>
      </view> -->
      <view class="button-contianer">
        <button class="button_normal" @click="save" v-if="!showPreview">
          <image class="button_img" src="../../static/images/icon_save.png"></image>保存
        </button>
        <button class="button_normal" open-type="share" @click="share" v-if="!showPreview">
          <image class="button_img" src="../../static/images/icon_share.png"></image>分享
        </button>
        <button class="button_normal" @click="collect">
          <image class="button_img" src="../../static/images/icon_collected.png"></image>{{isCollect?'取消收藏':'收藏'}}
        </button>
      </view>

    </view>

  </view>

</template>

<script setup lang="ts">
  import {
    ref
  } from 'vue';
  import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';

  import {
    baseURL
  } from '@/utils/http';
  import ImageList from '@/components/ImageList.vue'
  import videoPreview from '@/components/videoPreview.vue'
  import ssPreviewVue from '@/uni_modules/ss-preview/components/ss-preview/ss-preview.vue';
  import MumuPreviewOffce from '@/uni_modules/mumu-previewOffce/components/mumu-previewOffce/mumu-previewOffce.vue'
  import { collectFile } from '@/services/file';
  import { deleteFileCollectByCode } from '@/services/collect';
  import type { fileItem } from '@/types/files';
  import { useMemberStore } from '@/stores';
  import Func from '@/utils/func';
  import { getFileName, getFileType } from '@/utils/upload';


  // 获取会员信息
  const memberStore = useMemberStore()
  const userinfo : any = memberStore.getUserInfo()
  //是否展示底部操作栏
  const showOption = ref(false)
  const previewOffice = ref(null)
  //根据当前类型展示 视频 图片 pdf 或者doc
  const fileType = ref('')
  let fileCode = ''
  let dictTypeCode = ''//
  const showPreview = ref(false);//预览组件
  //预览链接 https://education.github.com/git-cheat-sheet-education.pdf
  const previewUrl = ref('')

  const officeUrl = ref('')
  //图片当前展示index
  const activeIndex = ref(0);
  const videoSrc = ref('')
  const coverUrl = ref('')
  //图片列表
  const mediaList = ref<fileItem[]>([]);
  //是否已收藏
  const isCollect = ref(false)
  const fileCollectCode = ref('')

  let filePath = ''//下载后的临时路劲
  // 获取页面参数
  const query = defineProps<{
    data ?: string
  }>()

  //页面初始化
  onLoad(() => {
    // 启用分享菜单（支持分享给好友和朋友圈）
    uni.showShareMenu({
      withShareTicket: true, // 是否使用带 shareTicket 的分享
      menus: ['shareAppMessage', 'shareTimeline'], // 可选：'shareAppMessage'（好友）、'shareTimeline'（朋友圈）
    })
    if (query.data) {

      const queryData = JSON.parse(query?.data)
      console.log(queryData)
      //是否展示下边操作行
      showOption.value = queryData.showOption || false
      //是否已收藏
      isCollect.value = queryData.isCollect
      fileCollectCode.value = queryData.fileCollectCode
      fileType.value = queryData.fileCtype
      console.log('fileType', fileType.value)
      fileCode = queryData.fileCode
      dictTypeCode = queryData.dictTypeCode
      showPreview.value = fileType.value == 'pdf' || fileType.value == 'xlsx' || fileType.value == 'docx'
      if (showPreview.value) {
        coverUrl.value = queryData.coverUrl //封面图
        previewUrl.value = queryData.fileUrl
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
      } else if (fileType.value == 'png' || fileType.value == 'jpg') {
        mediaList.value = []
        mediaList.value.push({
          url: queryData.fileUrl,
          fileId: queryData.fileCode
        })
      } else if (fileType.value == 'mp4') {
        videoSrc.value = queryData.fileUrl
        console.log(videoSrc.value)
      }
    }
  })
  const onChange = (e : any) => {
    console.log(e)
  }
  //加载成功
  const onSuccess = (e : any) => {
    if (e && e.path) {
      filePath = e.path
    }
    console.log('onSuccess', filePath)
    uni.hideLoading()
  }
  //下载文件失败
  const openFailed = () => {
    console.log('openFailed')
    uni.showToast({
      title: '加载文件失败',
      icon: 'none'
    })
  }
  //分享
  onShareAppMessage(() => {

    const viewerUrl = (fileType.value == 'png' || fileType.value == 'jpg') ? mediaList.value[0] : previewUrl.value
    return {
      title: '我正在使用云助手小程序', // 分享标题
      path: `/pagesMember/webview/webview?url=${viewerUrl}`, // 分享路径（可带参数）
      imageUrl: '/static/logo.jpg', // 分享图片（可选）
    }
  })
  //分享
  const share = () => {
    console.log('用户点击了分享按钮，但实际分享逻辑由 onShareAppMessage 控制')
  }
  //保存
  const save = () => {
    const saveUrl = (fileType.value == 'png' || fileType.value == 'jpg') ? mediaList.value[0].url : videoSrc.value
    console.log(saveUrl)
    if (fileType.value == 'png' || fileType.value == 'jpg') {
      uni.downloadFile({
        url: saveUrl,
        success: (res) => {
          console.log(res)
          if (res.statusCode === 200) {
            // 检查权限
            uni.getSetting({
              success: (settingRes) => {
                if (!settingRes.authSetting['scope.writePhotosAlbum']) {
                  console.log('请求权限')
                  // 请求权限
                  uni.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success: () => saveImage(res.tempFilePath, saveUrl),
                    fail: () => showAuthError()
                  });
                } else {
                  console.log('已有权限')
                  saveImage(res.tempFilePath, saveUrl);
                }
              }
            });
          }
        },
        fail: (error) => {
          console.log(error)
        }
      });
    } else if (fileType.value == 'mp4') {//视频

    }

  }
  // 保存图片到相册
  function saveImage(tempFilePath : any, saveUrl : any) {

    const fs = wx.getFileSystemManager();
    const targetPath = `${wx.env.USER_DATA_PATH}/${getFileName(saveUrl)}`;
    //  将临时文件保存到目标路径
    fs.saveFile({
      tempFilePath,
      filePath: targetPath,
      success: () => {
        // 3. 打开文件（可选）
        uni.saveImageToPhotosAlbum({
          filePath: targetPath,
          success: () => uni.showToast({ title: '保存成功', icon: 'success' }),
          fail: (err) => console.error('保存失败', err)
        });
      },
      fail: (err) => {
        console.error('保存失败:', err)

      }
    });

  }

  // 权限失败处理
  function showAuthError() {
    uni.showModal({
      title: '提示',
      content: '请授权保存到相册权限',
      success: (res) => {
        if (res.confirm) uni.openSetting(); // 引导用户手动授权
      }
    });
  }
  //收藏
  const collect = () => {
    if (isCollect.value) {
      //取消收藏
      deleteFileCollectByCode({ "fileCollectCode": fileCollectCode.value }).then(res => {

        if (res.success) {
          uni.showToast({
            title: '取消收藏成功',
            icon: 'none'
          })
          isCollect.value = false
        }
      })
      return
    }
    collectFile({
      userCode: userinfo.userCode,
      dictTypeCode,
      fileCode
    }).then((res : any) => {
      console.log(res)
      if (res.success) {
        fileCollectCode.value = res.dataObj
        console.log(fileCollectCode.value)
        isCollect.value = true
        uni.showToast({
          title: '收藏成功',
          icon: 'none'
        })
      }
    }).catch(e => {
      console.log(e)
    })
  }
  //重新打开文件
  const showFile = () => {
    showPreview.value = true
    //取缓存中的路径
    if (Func.isEmpty(filePath)) {
      wx.openDocument({
        filePath: filePath,
        fileType: getFileType(filePath),
        showMenu: true,
        success: () => {
          console.log('打开成功')

        }
      });
      return
    }
    console.log(previewOffice.value)
    if (previewOffice.value) {
      previewOffice.value.handleOpen(previewUrl.value)
    }
  }
</script>

<style lang="scss">
  .media_container {
    height: 75vh;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }


  .fileplaceholder {
    position: relative;
    width: 96%;
    margin-left: auto;
    margin-right: auto;
    height: 500rpx;
    background: rgba(84, 185, 204, 0.10);
    box-sizing: border-box;
    border-radius: 16rpx;
    border: 3rpx solid #00C1D1;
    overflow: hidden;
    /* 设置溢出隐藏 */


    .tag {
      text-align: center;
      line-height: 50rpx;
      height: 50rpx;
      width: 200rpx;
      left: 0;
      top: 0;
      color: white;
      font-size: 24rpx;
      position: absolute;
      border-top-left-radius: 20rpx;
      border-bottom-right-radius: 20rpx;
      background-color: #00C1D1;
    }

    .placeholder {
      width: 100%;
      height: 100%
    }

  }

  .bottom-contianer {
    position: fixed;
    bottom: 80rpx;
    width: 100%;
    z-index: 99;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .number-indicator {
    width: 222rpx;
    height: 68rpx;
    margin-left: auto;
    margin-right: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 40rpx;
    font-size: 26rpx;
    color: #1C253A;
    background: rgba(84, 185, 204, 0.20);
    border-radius: 16rpx;
  }

  .current {
    color: black;
  }

  .total {
    color: black
  }

  .slash {
    margin: 0 8rpx;
  }


  .button-contianer {
    display: flex;
    flex-direction: row;
    width: 90%;
    gap: 20rpx;
  }

  .button_normal {
    flex-grow: 1;
    color: #54B9CC;
    font-size: 30rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 2rpx solid #54B9CC;
  }

  .button_img {
    width: 44rpx;
    height: 44rpx;
    margin-right: 5rpx;
  }
</style>
